package com.shiyingzi.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.shiyingzi.common.Constants;
import com.shiyingzi.security.model.User;

public class SecurityInterceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		
		// 后台管理端拦截
		// 获取session
		HttpSession session = request.getSession(true);
		
		User user = (User) session.getAttribute(Constants.SESSION_USER);

		if (user == null) {
			String redirectPath = null;
			if (StringUtils.isNotBlank(request.getRequestURI())) {
				redirectPath = contextPath + "/login?url=" + StringUtils.replaceOnce(requestUri, contextPath, "");
			} else {
				redirectPath = contextPath + "/login";
			}
			response.sendRedirect(redirectPath);
			return false;
		} else {
			return true;
		}
	}

}
